<template>
  <n-data-table :columns :data />
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { NDataTable } from "naive-ui";
import { placeholderType } from "@/_utils";
import type { DataTableSelectionColumn, DataTableColumn } from "naive-ui";
import type { RowData } from "@/_utils";
import type { NaiveCrudOption } from "./interface";

const form = defineModel<RowData>("form", { default: () => ({}) });
const search = defineModel<RowData>("search", { default: () => ({}) });

const props = defineProps<{ option: NaiveCrudOption<any>, data: RowData[] }>();

const columns = computed(() => {
  const columns: DataTableColumn[] = props.option.columns
    .filter((col) => !col.hidden)
    .map((col) => ({
      key: col.key,
      title: col.renderTitle || col.title,
      align: col.align,
      titleAlign: col.titleAlign,
      fixed: col.fixed,
      width: col.width,
      titleRowSpan: col.titleRowSpan,
      className: col.className,
      ellipsis: col.ellipsis,
      resizable: col.resizable,
      maxWidth: col.maxWidth,
      minWidth: col.minWidth,
      cellProps: col.cellProps,
      rowSpan: col.rowSpan,
      colSpan: col.colSpan,
      render: col.render,
    }));
  if (props.option.select) {
    const select: DataTableSelectionColumn = {
      type: "selection",
      multiple: props.option.select === "multiple",
      width: props.option.selectWidth || 60,
      fixed: props.option.selectFixed ? "left" : undefined,
    };
    columns.unshift(select);
  }
  return columns;
});

const formItems = computed(() => {
  return props.option.columns
    .filter((col) => col.form ?? true)
    .map((col) => {
      const label = col.label || col.title;
      const type = col.type || "input";
      return {
        key: col.key,
        label,
        type,
        rules: col.rules,
        placeholder: col.placeholder || `${placeholderType(type)} ${label}`,
        disabled: col.disabled,
        order: col.order || 0,
      };
    })
    .sort((a, b) => a.order - b.order);
});

const searchItems = computed(() => {
  return props.option.columns
    .filter((col) => col.search)
    .map((col) => {
      const label = col.searchLabel || col.title;
      const type = col.searchType || col.type || "input";
      return {
        key: col.key,
        label,
        type,
        rules: col.searchRules || col.rules,
        placeholder:
          col.searchPlaceholder ||
          col.placeholder ||
          `${placeholderType(type)} ${label}`,
        disabled: col.searchDisabled,
        order: col.searchOrder || col.order || 0,
      };
    })
    .sort((a, b) => a.order - b.order);
});
</script>
